package com.syqc.monitor.ui.list

import android.Manifest
import android.content.Intent
import android.view.View
import android.widget.ImageView
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.permissionx.guolindev.PermissionX
import com.syqc.comlib.base.LazyFragment
import com.syqc.comlib.databinding.IncludeRecyclerMathBinding
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.utils.loadGif
import com.syqc.comlib.utils.startActivityTo
import com.syqc.comlib.utils.sub
import com.syqc.comlib.utils.subPlate
import com.syqc.comlib.utils.toast
import com.syqc.entity.GpsDetail
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentListBinding
import com.syqc.monitor.ui.alarm.NormalAlarmActivity
import com.syqc.monitor.ui.carinfo.CarInfoActivity
import com.syqc.monitor.ui.carmonitor.CarMonitorActivity
import com.syqc.monitor.ui.historyline.HistoryLineActivity
import com.syqc.monitor.ui.mile.MileActivity
import com.syqc.monitor.ui.photo.PhotosActivity
import com.syqc.monitor.ui.stopcar.StopCarActivity
import com.syqc.utils.Keys
import com.syqc.utils.ToolsUtil

/**
 *@Author Jasper
 *@Time   2020/11/12
 *@Desc   列表
 */
class ListMonitorFragment :
    LazyFragment<FragmentListBinding>(FragmentListBinding::inflate) {
    private lateinit var rvBinding: IncludeRecyclerMathBinding
    private val adapter: ListMonitorAdapter by lazy { ListMonitorAdapter() }
    private val itemPopup: ListItemPopup by lazy {
        ListItemPopup(
            requireContext(),
            false,
            clickListener
        )
    }
    private var locationEntity: GpsDetail? = null

    //全部数据
    private var allData: MutableList<GpsDetail> = mutableListOf()

    //空布局
    private val emptyView by lazy {
        val view = layoutInflater.inflate(
            R.layout.layout_empty_view,
            rvBinding.recyclerView,
            false
        )
        view.findViewById<ImageView>(R.id.ivNoData).loadGif(requireContext(), R.mipmap.ic_empty)
        view
    }

    override fun initView(view: View) {
        rvBinding = IncludeRecyclerMathBinding.bind(binding.root)
        rvBinding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        rvBinding.recyclerView.adapter = adapter
        adapter.setEmptyView(emptyView)
    }

    override fun initData() {

    }

    private fun search(key: String) {
        val upKey = key.uppercase()
        adapter.setList(allData.filter {
            if (adapter.isPlate) {
                it.carPlate.uppercase().contains(upKey)
            } else {
                it.carName.uppercase().contains(upKey)
            }
        })

    }

    override fun initEvent() {
        binding.ivClear.setOnClickListener {
            binding.editSearch.setText("")
        }

        binding.tvSearch.setOnClickListener {
            search(binding.editSearch.text.toString())
        }

        binding.editSearch.doAfterChanged {
            if (it.isNullOrEmpty()) {
                adapter.setList(allData)
            }
            binding.ivClear.isInvisible = it.isNullOrEmpty()
        }

        adapter.setCallBack(object : ListMonitorAdapter.ListMonitorCallback {
            override fun callBack(item: GpsDetail) {
                locationEntity = item
                itemPopup.showAtLocation(
                    requireActivity().window.decorView,
                    sub(
                        if (adapter.isPlate) {
                            item.carPlate
                        } else {
                            item.carName
                        }, 10
                    )
                )

            }

            override fun mapCallbacks(item: GpsDetail) {
                locationEntity = item
                when (item.state) {
                    "1", "5" -> showToast(R.string.toast_car_state_no_location)
                    else -> toCarMonitor()
                }
            }

        })

    }

    fun setPlatName(boolean: Boolean) {
        adapter.isPlate = boolean
    }

    fun setData(data: MutableList<GpsDetail>) {
        allData.clear()
        if (data.isEmpty()) {
            adapter.setEmptyView(emptyView)
        } else {
            allData.addAll(data)
        }
        adapter.setList(allData)
    }

    fun clear() {
        adapter.data.clear()
        adapter.notifyDataSetChanged()
        adapter.setEmptyView(emptyView)
    }

    fun notifyDataSetChanged() {
        adapter.notifyDataSetChanged()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        adapter.data.clear()
    }

    private val clickListener = View.OnClickListener { v ->
        if (locationEntity == null || ToolsUtil.isFastClick()) return@OnClickListener
        when (v.id) {
            R.id.tvLMPopLine -> {
                startActivity(HistoryLineActivity::class.java)
            }
            R.id.tvLMPopInfo -> {
                startActivity(
                    Intent(
                        requireContext(),
                        CarInfoActivity::class.java
                    ).putExtra(Keys.INTENT_CAR_ID, locationEntity!!.carId)
                )
//                LiveDataBus.get().with("CarInfo").postValue(locationEntity)
            }
            R.id.tvLMPopMile -> {
                startActivity(MileActivity::class.java)
            }
            R.id.tvLMPopAlarm -> {
                startActivity(NormalAlarmActivity::class.java)
            }
            R.id.tvLMPopPhoto -> {
                startActivity(PhotosActivity::class.java)
            }
            R.id.tvLMPopStopCar -> {
                startActivity(StopCarActivity::class.java)
            }
        }


    }

    private fun toCarMonitor() {
        if (ToolsUtil.isFastClick()) return
        startToCarMonitor()
    }

    private fun startToCarMonitor() {

        PermissionX.init(this).permissions(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ).request { allGranted, grantedList, deniedList ->
            if (allGranted) {
                startActivityTo<CarMonitorActivity>(requireContext()){
                    putExtra(Keys.INTENT_CAR_ID, locationEntity!!.carId)
                    putExtra(Keys.INTENT_IS_VIDEO, locationEntity!!.videos)
                    putExtra(Keys.INTENT_PLATE, subPlate(locationEntity!!.carPlate, 14))
                }

            } else {
                getString(
                    R.string.toast_persission_open,
                    getString(R.string.permission_location)
                ).toast(
                    requireContext()
                )
            }
        }

    }

    private fun startActivity(zClass: Class<*>) {
        startActivity(
            Intent(requireContext(), zClass)
                .putExtra(Keys.INTENT_CAR_ID, locationEntity!!.carId)
                .putExtra(Keys.INTENT_PLATE, subPlate(locationEntity!!.carPlate, 14))
        )
    }


}